﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;

namespace Nirvana
{
    [RequireComponent(typeof(UIRawImageLoadByURL))]
    [AddComponentMenu("Nirvana/UI/Bind/Variable Bind RawImage URL")]
    public class UIVariableBindRawImageURL : UIVariableBind
    {
        private static Logger logger = LogSystem.GetLogger("UIVariableBindRawImageURL");
        [SerializeField]
        [VariableName(UIVariableType.String)]
        private string urlBind;
        private UIRawImageLoadByURL _loadimageurl;
        private UIVariable _variable;

        protected override void BindVariables()
        {
            Assert.IsNull<UIVariable>(this._variable);
            if (!string.IsNullOrEmpty(this.urlBind))
            {
                this._variable = base.FindVariable(this.urlBind);
                if (this._variable == null)
                {
                    logger.LogWarning("{0} can not find a variable {1}", new object[]
                    {
                        base.name,
                        this.urlBind
                    });
                }
                else
                {
                    this._variable.OnValueInitialized += this.OnValueInitialized;
                    this._variable.OnValueChanged += this.OnValueInitialized;
                    this._variable.Add(this);
                    this.OnValueInitialized();
                }
            }
        }
        protected override void UnbindVariables()
        {
            if (this._variable != null)
            {
                this._variable.OnValueInitialized -= this.OnValueInitialized;
                this._variable.OnValueChanged -= this.OnValueInitialized;
                this._variable.Remove(this);
                this._variable = null;
            }
        }

        private  void OnValueInitialized()
        {
            if (this._loadimageurl == null)
            {
                this._loadimageurl = base.GetComponent<UIRawImageLoadByURL>();
            }
            if (this._loadimageurl != null)
            {
                string @string = this._variable.GetString();
                this._loadimageurl.URL = @string;
            }
        }

    }
}

